import User from '../models/user'
import {Success,Fail} from "../utils/responseUtil"
import {BizAuthError} from "../types/Exception"
import AppResponse from "response"
import Hapi from '@hapi/hapi'
import fs from 'fs'
import path from "path"
import jose from 'jose'
import {sendAuthEmail,genAuthCode} from '../utils/app_utils';
import user from "../models/user";

export enum registerType {
    email, normal, phone
}

// 用户验证相关服务（登录，注册，找回密码，绑定账号）
export default class AuthService {
    // 校验用户名
    private static validateUserName(username: string): boolean {
        return username.length >= 10 &&
            /^[0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]+$/.test(username)
    }
    // 校验密码
    private static validatePassword(password: string): boolean {
        return password.length >= 6
    }
    // 邮箱注册
    static async emailRegister(username: string, password: string, request: Hapi.Request): Promise<AppResponse> {
        if(!this.validateUserName(username)) {
            return Fail(BizAuthError.UsernameInvalid())
        }
        if(!this.validatePassword(password)) {
            return Fail(BizAuthError.PasswordInvalid())
        }
        let qUser = await User.findOne({username})
        if(qUser !== null) {
            return Fail(BizAuthError.UserExistError())
        }
        let authCode = ''
        try {
            authCode = genAuthCode(10)
        } catch (e) {
            console.error(e)
        }

        let iUser = new User({username, password, authCode, status: 0})
        await iUser.save()
        // send email
        let authLink = `${request.url.origin}/auth/email?authCode=${authCode}&id=${iUser._id}`
        sendAuthEmail(username, iUser._id, authLink)
        return Success("success")
    }

    // 邮箱验证
    static async emailAuth(userId: string, authCode: string): Promise<AppResponse> {
        if(userId === null || userId.length === 0
            || authCode === null || authCode.length === 0) {
            return Fail(BizAuthError.EmailAuthFail())
        }
        let qUser = await User.findOne({_id: userId});
        if(qUser){
            if(authCode === qUser.authCode) {
                await qUser.update({status: 1})
                return Success("认证成功")
            } else {
                return Fail(BizAuthError.EmailAuthFail())
            }
        } else {
            return Fail(BizAuthError.EmailAuthFail())
        }
    }

    // 登录
    static async login(username: string, password: string): Promise<AppResponse> {
        if(!this.validateUserName(username)) {
            return Fail(BizAuthError.UsernameInvalid())
        }
        let qUser = await User.findOne({username})
        if(!qUser) {
            return Fail(BizAuthError.UserNotExist())
        }
        if(qUser.status === 0) {
            return Fail(BizAuthError.UserUnauthed())
        }
        if(qUser.password !== password) {
            return Fail(BizAuthError.PasswordWrong())
        }
        let pt = path.join(__dirname, '../../jwtsign.key')
        let pk = fs.readFileSync(pt,'utf8');
        let payload = {
            role: 'user',
            id: qUser.id
        }
        console.log(payload)
        let token = jose.JWT.sign(payload, pk, {
            expiresIn: '5m'
        })
        return Success({token})
    }
}
